package org.hawk.gwt.ppc.reflect.lang;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.hawk.gwt.ppc.reflect.emul.java.lang.InternalError;

/**
 * Provides access to reflect package. Can be accessed only from
 * {@link ClassDelegate} and used only for hosted mode (for debug purposes).
 * 
 * @author alex.bereznevatiy@gmail.com
 */
public class ReflectAccessor {

	public <T> Constructor<T> createConstructor(Object accessor,
			ClassDelegate<T> cls, String signature) throws SecurityException {
		try {
			return cls.toClass().getDeclaredConstructor(
					ClassDelegate.unmarshalSignature(signature));
		} catch (NoSuchMethodException ex) {
			throw new InternalError(ex);
		}
	}

	public Field createField(Object accessor, ClassDelegate<?> cls,
			String signature) {
		try {
			return cls.toClass().getDeclaredField(signature);
		} catch (NoSuchFieldException ex) {
			throw new InternalError(ex);
		}
	}

	public Method createMethod(Object accessor, ClassDelegate<?> cls,
			String signature) {
		try {
			int i = signature.indexOf('(');
			String name = signature;

			if (i >= 0) {
				name = signature.substring(0, i);
			}
			return cls.toClass().getDeclaredMethod(name,
					ClassDelegate.unmarshalSignature(signature));
		} catch (NoSuchMethodException ex) {
			throw new InternalError(ex);
		}
	}
}
